<template>
  <zx-container>
    <template #zx-primary-search>
      <zx-search-form
        v-model:formData="searchParams"
        :formItems="formItems"
        v-model:page="pages.page"
        @search="searchTable"
      />
    </template>
    <template #zx-primary-header>
      <TableTitle title="FB投放个号管理列表">
        <div>
          <!-- // 使用千分符标识数字 -->
          <span class="title-intro">
            待使用FB个号资源：{{ Number(unused_total).toLocaleString() }}个
          </span>
          <el-button
            type="primary"
            link
            @click="
              linkTo(
                'https://alidocs.dingtalk.com/i/nodes/QOG9lyrgJPj6dQoxUE5woMajWzN67Mw4?utm_scene=team_space'
              )
            "
          >
            Access Token填写教程
          </el-button>
          <el-button
            type="primary"
            icon="Download"
            :loading="exportLoading"
            @click="exportData"
          >
            导出
            <span v-if="exportLoading">（{{ exportProgress }}%）</span>
          </el-button>
        </div>
      </TableTitle>
    </template>
    <template #zx-primary-container>
      <zx-table
        ref="tableRef"
        height="100%"
        :loading="loading"
        :columns="columns"
        :data="tableData"
        minWidth="150"
      >
        <template #token_enable="{ row }">
          <span v-if="row.token_enable === true" class="success-text">
            {{ TOKEN_STATUS_OBJ[row.token_enable]?.label || DEFAULT_TEXT }}
          </span>
          <span v-else-if="row.token_enable === false" class="danger-text">
            {{ TOKEN_STATUS_OBJ[row.token_enable]?.label || DEFAULT_TEXT }}
          </span>
          <span v-else>{{ DEFAULT_TEXT }}</span>
        </template>
      </zx-table>
      <zx-pagination
        v-model:page="pages.page"
        v-model:size="pages.per_page"
        :total="total"
        @change="getTableData"
      />
    </template>

    <!-- 登录加载 -->
    <LoginLoading v-model:show="showLoginLoading" :info="activeRow" />
    <!-- 申请详情 -->
    <DetailDialog
      ref="DetailDialogRef"
      v-model:show="showDetail"
      :activeRow="activeRow"
      @edit="edit"
      @openToken="openToken(activeRow)"
    />
    <!-- 申请编辑 -->
    <EditDialog
      v-model:show="showEdit"
      :activeRow="activeRow"
      @reload="getTableData"
    />
    <!-- 二次验证 -->
    <ValidDialog v-model:show="showValid" :activeRow="activeRow" />
    <!-- 邮箱 -->
    <EmailDialog v-model:show="showEmail" :activeRow="activeRow" />
    <!-- 更新Token -->
    <TokenDialog
      v-model:show="showToken"
      :activeRow="activeRow"
      @login="login(activeRow)"
      @reload="tokenSuccess"
    />
  </zx-container>
</template>

<script setup>
import { useTable } from 'zhixin-ui';
import {
  companyResourceFb_accountList,
  companyResourceFb_accountExport,
  companyResourceFb_accountReceive,
  companyResourceFb_accountUpdate,
  companyResourceFb_accountCheck_current_token
} from '@/api/resources.js';
import { companyFb_account_typeAll } from '@/api/system';
import { formItems, columns, searchParams, injectData } from './tableConst';
import TableTitle from '@/components/TableTitle';
import {
  PAGES,
  INIT_ORANIZE_PARAMS,
  DEFAULT_TEXT,
  TOKEN_STATUS_LIST
} from '@/utils/const';
import { exportExcel } from '@/utils';
import LoginLoading from '@/components/LoginLoading';
import { ElMessage, ElMessageBox } from 'element-plus';
import DetailDialog from './DetailDialog';
import EditDialog from './EditDialog';
import ValidDialog from './ValidDialog';
import EmailDialog from './EmailDialog';
import TokenDialog from './TokenDialog';

const TOKEN_STATUS_OBJ = {};
TOKEN_STATUS_LIST.forEach(item => (TOKEN_STATUS_OBJ[item.value] = item));

const props = defineProps({
  activeOranize: {
    type: Object,
    default: () => {}
  }
});

// 表格hooks
const unused_total = ref(0);
const tableRef = ref();
const { loading, tableData, pages, total, getTableData } = useTable(
  companyResourceFb_accountList,
  {
    tableRef,
    searchParams,
    formItems,
    autorun: false,
    pages: PAGES(),
    onSuccess(res) {
      unused_total.value = res.data?.unused_total || 0;
    }
  }
);

// 查询相关
function initSearchParams() {
  pages.value.page = 1;
  INIT_ORANIZE_PARAMS(searchParams, props.activeOranize);
}
function searchTable(type) {
  if (type === 'reset') initSearchParams();
  getTableData();
}
function initTable(keep) {
  if (!keep) initSearchParams();
  getTableData();
}

// 导出
const exportLoading = ref(false);
const exportProgress = ref(0);
function exportData() {
  const params = JSON.parse(JSON.stringify(searchParams));
  delete params.applyRange;

  exportExcel({
    loading: exportLoading,
    api: companyResourceFb_accountExport,
    params,
    formItems,
    progress: exportProgress
  });
}

// 跳转
function linkTo(url) {
  window.open(url);
}

// 登录
const showLoginLoading = ref(false);
async function login(row) {
  activeRow.value = row;
  row.loginLoading = true;
  try {
    const tokenRes = await companyResourceFb_accountCheck_current_token({
      id: row.id
    });
    if (tokenRes.data) return openLoginLoading();

    ElMessageBox({
      title: '登录个号',
      message: '个号Token已失效，请及时更新Token信息，以便于及时获取广告数据',
      type: 'warning',
      confirmButtonText: '确认并登录',
      showCancelButton: true
    }).then(() => {
      openLoginLoading();
    });
  } finally {
    delete row.loginLoading;
  }
}
function openLoginLoading() {
  showLoginLoading.value = true;
}

// 详情
const showDetail = ref(false);
const activeRow = ref({});
function openDetail(row) {
  activeRow.value = row;
  showDetail.value = true;
}

// 编辑
const showEdit = ref(false);
function edit(row) {
  activeRow.value = row;
  showDetail.value = false;
  showEdit.value = true;
}

// 领取
async function receive(row) {
  row.receiveLoading = true;
  try {
    const tokenRes = await companyResourceFb_accountCheck_current_token({
      id: row.id
    });
    const tokenFlag = tokenRes.data;
    let msg = '';
    if (tokenFlag) {
      msg = `请确认是否领取FB投放个号资源？<br>领取后将绑定成为使用人员。`;
    } else {
      msg = `请确认是否领取FB投放个号资源？<br>领取后，请及时填写Access Token信息，以便于获取广告投放数据。`;
    }
    ElMessageBox({
      title: '领取个号',
      dangerouslyUseHTMLString: true,
      message: msg,
      type: 'warning',
      confirmButtonText: '确认领取',
      showCancelButton: true,
      beforeClose: (action, instance, done) => {
        if (action !== 'confirm') return done();
        instance.confirmButtonLoading = true;
        companyResourceFb_accountReceive({ id: row.id })
          .then(() => done())
          .finally(() => (instance.confirmButtonLoading = false));
      }
    }).then(() => {
      $msg.success('领取成功');
      getTableData();
    });
  } finally {
    delete row.receiveLoading;
  }
}

// 二次验证
const showValid = ref(false);
function openValid(row) {
  activeRow.value = row;
  showValid.value = true;
}

// 邮箱
const showEmail = ref(false);
function openEmail(row) {
  activeRow.value = row;
  showEmail.value = true;
}

// 弃用
function giveUp(row) {
  ElMessageBox({
    title: '弃用个号',
    dangerouslyUseHTMLString: true,
    message: `请确认是否弃用该FB个号资源？<br>弃用前请先解除广告账户和弃用个号的绑定关系；弃用后将取消使用人员绑定记录，且将无法登录个号。`,
    type: 'warning',
    confirmButtonText: '确认弃用',
    showCancelButton: true,
    beforeClose: (action, instance, done) => {
      if (action !== 'confirm') return done();
      instance.confirmButtonLoading = true;
      companyResourceFb_accountUpdate({ id: row.id })
        .then(() => done())
        .finally(() => (instance.confirmButtonLoading = false));
    }
  }).then(() => {
    $msg.success('弃用成功');
    getTableData();
  });
}

// 更新token
const showToken = ref(false);
function openToken(row) {
  activeRow.value = row;
  showToken.value = true;
}

// token更新成功后
const DetailDialogRef = ref();
function tokenSuccess() {
  getTableData();
  if (showDetail.value) {
    DetailDialogRef.value?.initForm();
  }
}

// 获取所有查询下拉
function getOptions() {
  // 个号类型
  companyFb_account_typeAll().then(res => {
    const resData = res.data || [];
    formItems.fb_account_type.options = [
      { label: '全部', value: undefined },
      ...resData.map(item => {
        return { label: item.name, value: item.id };
      })
    ];
  });
}

defineExpose({ initTable, getOptions });
injectData({
  receive,
  login,
  openDetail,
  openValid,
  openEmail,
  openToken,
  giveUp
});
</script>

<style lang="scss" scoped>
:deep(.oms-table-title-box) {
  position: relative;
}
.title-intro {
  position: absolute;
  left: 220px;
  font-size: 14px;
}
</style>
<style>
.fb-nm-table-btn-dropdown .el-dropdown-menu__item {
  justify-content: center;
  line-height: 24px;
}
.fb-nm-table-btn-dropdown .el-dropdown-menu__item--divided {
  margin: 0;
}
</style>
